import Vue from 'vue'
import Vuex from 'vuex'
import {getRequest} from "../utils/api";
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
import { Notification } from 'element-ui';
Vue.use(Vuex);
const now = new Date();



const store=new Vuex.Store({
    state:{
        routes:[],
        sessions:{},
        admins:[],
        stomp:null,
      /*  sessions:[{
            id:1,
            user:{
                name:'示例介绍',
                img:'https://p1.ssl.qhimgs1.com/sdr/400__/t016285e89909a8c421.jpg'
            },
            messages:[{
                content:'Hello，这是一个基于Vue + Vuex + Webpack构建的简单chat示例，聊天记录保存在localStorge, 有什么问题可以通过Github Issue问我。',
                date:now
            },{
                content:'项目地址(原作者): https://github.com/coffcer/vue-chat',
                date:now
            },{
                content:'本项目地址(重构): https://github.com/is-liyiwei',
                date:now
            }]
        },{
            id:2,
            user:{
                name:'webpack',
                img:'https://p2.ssl.qhimgs1.com/sdr/400__/t0134e25cbac86e65d2.gif'
            },
            messages:[{
                content:'Hi，我是webpack哦',
                date:now
            }]
        }],*/
        currentSession:null,
        filterKey:'',
        /*当前用户*/
        currentAdmin:JSON.parse(window.sessionStorage.getItem('user')),
        idDot:{}
    },
        getters:{

        },

    //同步
    mutations:{
        INIT_ADMIN(state,admin){
            state.currentAdmin=admin;
        },
        INIT_CURRENTADMIN(state,admin){
            state.currentAdmin=admin;
        },
        initRoutes(state,data){
            state.routes=data;
        },


        changeCurrentSession (state,currentSession) {
            state.currentSession = currentSession;
            /*取消小红点*/
            Vue.set(state.idDot,state.currentAdmin.username+'#'+state.currentSession.username,false)
        },
        addMessage (state,msg) {
            /*mss[0].content可拿到消息内容*/
            let mss=state.sessions[state.currentAdmin.username+'#'+msg.to];
            if(!mss){
                //state.sessions[state.currentAdmin.username+'#'+msg.to]=[];
                //监听sessions变化
                Vue.set(state.sessions,state.currentAdmin.username+'#'+msg.to,[]);
            }
            state.sessions[state.currentAdmin.username+'#'+msg.to].push({
                content:msg.content,
                date:new Date(),
                self:!msg.notSelf
            })

           /* .messages.push({
                content:msg,
                date: new Date(),
                self:true
            })*/
        },
        INIT_DATA (state) {
            let data = localStorage.getItem('vue-chat-session');
            //console.log(data)
            if (data) {
                state.sessions = JSON.parse(data);
            }
        },
        INIT_ADMINS(state,data){

            state.admins=data;
        }
    },
    //异步
    actions:{
        initData (context) {
            getRequest('/system/admin/').then(resp=>{
                if (resp){
                    context.commit('INIT_ADMINS',resp);
                }
            });
        },
        //此函数加载菜单时被调用
        connect(context){
            /*创建后端端点  后端spring-web可能需要2.3.12RELEASE 不然可能出现sockjs报错*/
            context.state.stomp=Stomp.over(new SockJS('ws/ep'));
            let token = window.sessionStorage.getItem('tokenStr');
            /*连接  参数  成功回调  失败回调*/
            context.state.stomp.connect({"Auth-Token":token},success=>{
                /*成功就订阅消息频道 拿到消息就用消息体打出 /user  默认R*/
                context.state.stomp.subscribe('/user/queue/chat',msg=>{
                    let receiveMsg=JSON.parse(msg.body);
                    //未读状态
                    if (!context.state.currentSession || receiveMsg.from !=context.state.currentSession.username){
                       Notification.info({
                            title:"【"+ receiveMsg.formNickName + "】发来一条消息",
                            message: receiveMsg.content.length>10?
                                receiveMsg.content.substr(0,10):receiveMsg.content,
                                position:'bottom-right'
                        });
                       /*设置小红点*/
                        Vue.set(context.state.idDot,context.state.currentAdmin.username+'#'+receiveMsg.from,true)
                    }
                    receiveMsg.notSelf =true;
                    receiveMsg.to = receiveMsg.from;
                    context.commit('addMessage',receiveMsg);
                })
            },error=>{
            })
        }
    },
})



store.watch(function (state) {
    return state.sessions
},function (val) {
    console.log('CHANGE: ', val);
    localStorage.setItem('vue-chat-session', JSON.stringify(val));
},{
    deep:true/*这个貌似是开启watch监测的判断,官方说明也比较模糊*/
})


export default store;

